import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { userLogin } from '@/api/user';
import { createBrowserHistory } from "history";
import { message } from "antd";
const history = createBrowserHistory();
export const doLogin = createAsyncThunk(
  'user/userLogin',
  async (params: any) => {
    const res = await userLogin(params)
    return res.data
  }
)

// 定义初始状态
const initialState = {
  token: localStorage.getItem('token') || '',
  role: localStorage.getItem('role') || '',
  userInfo: localStorage.getItem('userInfo')
    ?
    JSON.parse(localStorage.getItem('userInfo') as string)
    :
    {},
  
}
export const userSlice = createSlice({
  name: 'user',
  initialState,
  // 存储 actionCreator 是同步 用来修改数据的
  reducers: {
  },
  // 定义 异步 actionCreator
  extraReducers: (builder) => {
    builder.addCase(doLogin.fulfilled, (state, {payload}) => {
      if (payload.code === 200) {
      
        const { token, userInfo, role } = payload.data;
        // 缓存起来
        localStorage.setItem('token', token);
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
        localStorage.setItem('role', role);
        state.role = role;
        state.token=token;
        state.userInfo = userInfo;
        message.success(payload.msg, 2, () => {
          // 跳转到首页
          history.replace('/dashBoard', {replace: true})
          history.go(0)
        })
      } else {
        message.error(payload.msg)
      }
    
      
    })
  }
})

// actionCreator拿出来并暴露出去
export const { } = userSlice.actions

export default userSlice.reducer